// pages/goods/index.js
var app = getApp();
const util = require('../../utils/util.js');
import * as echarts from '../../ec-canvas/echarts';

function setChart(chart, rate, sumSuccess) {
    var option = {
        backgroundColor: "#ffffff",
        series: [{
            label: {
                normal: {
                    fontSize: 9,
                    show: true,
                    position: 'inside'
                }
            },
            clockwise: false,
            color: ['rgba(45, 152, 253, 1)', 'rgba(229, 243, 255, 1)'],
            type: 'pie',
            center: ['50%', '50%'],
            data: [{
                value: rate,
                name: rate + '%'
            }, {
                value: sumSuccess,
                name: sumSuccess + '%'
            }]
        }]
    };
    chart.setOption(option);
}

function setTrend(chart, countId, createTime) {
    console.log(countId)
    const option = {
        xAxis: {
            data: createTime
        },
        yAxis: {
            type: 'value',
            splitLine: {
                show: false,
            },
            splitArea: {
                show: true,
                areaStyle: {
                    color: ['rgba(238, 248, 255, 1)', 'rgba(226, 244, 255, 1)']
                }
            },
        },
        lineStyle: {
            color: '#7DCEFF',
            width: 1
        },
        areaStyle: {
            color: {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0,
                colorStops: [{
                    offset: 0,
                    color: 'rgba(125, 206, 255, 0.14)' // 0% 处的颜色
                }, {
                    offset: 1,
                    color: 'rgba(125, 206, 255, 1)' // 100% 处的颜色
                }],
                global: false
            }
        },
        grid: {
            top: '10',
            left: '0',
            right: '0',
            bottom: '0',
            containLabel: true
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        series: [{
            name: '已铺货',
            data: countId,
            type: 'line',
            areaStyle: {},
            itemStyle: {
                color: "rgba(69, 184, 255, 1)"
            }
        }, ]
    };
    chart.setOption(option)
}

Page({
    /**
     * 页面的初始数据
     */
    data: {
        parameter: {
            'navbar': '1',
            'return': '2',
            'title': '海螺号工蜂',
            'color': true,
            'class': false
        },
        isSearchList: true,
        navH: '', //navbar高度
        tabbar: '',
        winWidth: '', //屏幕宽度
        winHeight: '', //屏幕高度
        await: 'none',
        dateSelector: app.MultipleSelectDate,
        date: "选择时间",
        startTime: '',
        endTime: '',
        days: '1',
        start_date: "",
        currTab: 0, //顶部tab切换
        staNav: 0, //状态tab切换,订单状态
        pageH: app.globalData.pageHeight,
        hiddenName: false,
        store: { //铺店概况饼图
            lazyLoad: true,
            pageNum: 1
        },
        goods: { //铺货概况饼图
            lazyLoad: true,
            pageNum: 1
        },
        trend: { //铺货次数趋势折线图
            lazyLoad: true
        },
        allstore: '',
        dateIndex: '', //点击选择时间
        dealerId: -1, //店铺id
        dealerName: '', //店铺名称
        pic: "https://pic.localhost.com/",
        executorUserId: '', //工蜂id
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        // 获取屏幕数据
        wx.getSystemInfo({
            success: res => {
                that.setData({
                    navH: res.statusBarHeight * (750 / res.windowWidth) + 97,
                    winHeight: res.windowHeight,
                    winWidth: res.windowWidth,
                    tabbar: (res.screenHeight - res.windowHeight - res.statusBarHeight) * res.pixelRatio
                })
            },
            fail(err) {}
        })
        this.oneComponent = this.selectComponent('#mychart-dom-bar1');
        this.twoComponent = this.selectComponent('#mychart-dom-bar2');
        this.threeComponent = this.selectComponent('#mychart-dom-line');
        this.init_one();
        this.init_two();
        this.init_three();
        this.getHeight1()
    },
    onShow: function () {
        var that = this;
        wx.getStorage({
            key: 'userInfo',
            success(res) {
                that.setData({
                    executorUserId: res.data.id,
                    topNum: 0,
                    allstore: '',
                    ['store.pageNum']: 1,
                    ['goods.pageNum']: 1
                })
                that.awaitGoods(); //任务执行铺货
                that.allStore(); //全部店铺
                that.survey(1); //佣金概况
                that.one_pie();
                that.two_pie();
                that.trend();
            }
        })
    },
    //  获取高度适配列表高度
    getHeight1() {
        var that = this;
        wx.createSelectorQuery().selectAll('.Navitem, .State').boundingClientRect().exec(function (res) {
            that.setData({
                listHeight: res[0][0].height + res[0][1].height + wx.getStorageSync('footerHeight')
            })
        })
    },
    // 滚动到底部加载更多
    storeLower() {
        var pageNum = Number(this.data.store.pageNum) + 1;
        this.setData({
            ['store.pageNum']: pageNum
        })
        this.allStore()
    },
    // 滚动到底部加载更多
    goodsLower() {
        var pageNum = Number(this.data.goods.pageNum) + 1;
        this.setData({
            ['goods.pageNum']: pageNum
        })
        this.awaitGoods()
    },
    //全部店铺
    allStore(e) {
        var that = this,
            value = "",
            pageNum = 1,
            list = [];
        try {
            value = e.detail.value
        } catch (e) {}
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'worker/distribution/getDealerName',
            q: {
                dealerName: value, //店铺名称
                pageNum: that.data.store.pageNum, //页码
                pageSize: 10, //每页数据数量
                userId: that.data.executorUserId
            }
        }), res => {
            pageNum = res.data.pageNum;
            if (pageNum == 1) {
                list = res.data.data;
            } else {
                list = app.SplitArray(res.data.data ? res.data.data : [], that.data.allstore) //分页合并数组
            }
            that.setData({
                allstore: list,
                'store.pageNum': pageNum
            })
        }, (res) => {})
    },
    // 选择店铺
    selectShop: function (e) {
        this.setData({
            dealerId: e.currentTarget.dataset.id,
            awaitgoods: ''
        })
        this.btn()
        this.awaitGoods();
    },
    //任务执行铺货
    awaitGoods() {
        var that = this,
            pageNum = 1,
            list = [];
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'worker/distribution/getTaskOrder',
            q: {
                dealerId: that.data.dealerId, //店铺id
                pageNum: that.data.goods.pageNum ? that.data.goods.pageNum : 1, //页码
                pageSize: 5, //每页数据数量
                status: that.data.staNav, //订单状态
                userId: that.data.executorUserId
            }
        }), res => {
            pageNum = res.data.pageNum;
            if (pageNum == 1 || pageNum == undefined) {
                if (res.data.length == 0) {
                    list = []
                } else {
                    list = res.data.data
                }
            } else {
                list = app.SplitArray(res.data.data ? res.data.data : [], that.data.awaitgoods) //分页合并数组
            }
            that.setData({
                awaitgoods: list,
                ['goods.pageNum']: pageNum
            })
        }, (res) => {})
    },
    //初始化铺货饼图
    init_one: function (sumSuccess, rate) {
        this.oneComponent.init((canvas, width, height, dpr) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            setChart(chart, sumSuccess, rate)
            this.chart = chart;
            return chart;
        });
    },
    init_two: function (sumSuccess, rate) {
        this.twoComponent.init((canvas, width, height, dpr) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr
            });
            setChart(chart, sumSuccess, rate)
            this.chart = chart;
            return chart;
        });
    },
    // 初始化折线图
    init_three: function (countId, createTime) {
        this.threeComponent.init((canvas, width, height, dpr) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            setTrend(chart, countId, createTime)
            this.chart = chart;
            return chart;
        });
    },
    //铺店饼图获取添加数据
    one_pie: function () {
        var _this = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'workerBeeInfo/findWorkerShopOverview/',
            q: {
                executorUserId: _this.data.executorUserId
            }
        }), res => {
            var rate = [];
            var sumSuccess = [];
            _this.setData({
                countGoodsId: res.data[0].countGoodsId,
                countDealerId: res.data[0].countDealerId,
                waitForDealer: res.data[0].waitForDealer,
                succesDealer: res.data[0].succesDealer,
            })
            rate = res.data[0].rate.toFixed(2);
            sumSuccess = (100 - rate).toFixed(2);
            _this.init_one(sumSuccess, rate)
        }, (res) => {})
    },
    // 铺货饼图获取添加数据
    two_pie: function () {
        var _this = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'workerBeeInfo/findWorkerShopOverviews/',
            q: {
                executorUserId: _this.data.executorUserId
            }
        }), res => {
            var rate = [];
            var sumSuccess = [];
            _this.setData({
                countGoodsIds: res.data[0].countGoodsId,
                countDealerIds: res.data[0].countDealerId,
                waitForDealers: res.data[0].waitForDealer,
                succesDealers: res.data[0].succesDealer,
            })
            rate = res.data[0].rate.toFixed(2);
            sumSuccess = (100 - rate).toFixed(2);
            _this.init_two(sumSuccess, rate)
        }, (res) => {})
    },
    //折线图获取添加数据
    trend: function () {
        var _this = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'workerBeeInfo/findWorkerBeeTrend/',
            q: {
                executorUserId: _this.data.executorUserId
            }
        }), res => {
            var createTime = [];
            var countId = [];
            for (var i = 0; i < res.data.length; ++i) {
                createTime[i] = res.data[i].createTime.match(/-\d{1,2}-\d{1,2}/g).toString().slice(1);
                countId[i] = res.data[i].countId;
            }
            console.log(countId)
            console.log(createTime)
            _this.init_three(countId, createTime)
        }, (res) => {})
    },
    /* 佣金概况 */
    survey(dateIndex) {
        var that = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'workerBeeInfo/',
            q: {
                executorUserId: that.data.executorUserId, //业务员id
                days: dateIndex,
                startTime: that.data.startTime,
                endTime: that.data.endTime
            }
        }), res => {
            that.setData({
                waitMoney: res.data[0].waitMoney,
                obtainMoney: res.data[0].obtainMoney,
                refundMoeny: res.data[0].refundMoeny,
            })

        }, (res) => {})
    },
    //订单详情
    goodsInfo(e) {
        var that = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'worker/distribution/getOrder',
            q: {
                goodsId: e.currentTarget.dataset.goodsid,
                dealerId: e.currentTarget.dataset.dealerid,
                userId: that.data.executorUserId
            }
        }), res => {
            console.log(res)
            that.setData({
                orderinfo: res.data,
                status: res.data.status,
                dealer: res.data.dealer,
                goods: res.data.goods
            })
            that.cancle();
        }, (res) => {})
    },
    //拒绝订单
    refuse(e) {
        var that = this;
        app.baseGet(app.U({
            m: 'api',
            c: 'task',
            a: 'worker/distribution/refuseTaskOrder',
            q: {
                goodsId: e.currentTarget.dataset.goodsid,
                dealerId: e.currentTarget.dataset.dealerid,
                userId: that.data.executorUserId
            }
        }), res => {
            that.cancle();
            that.awaitGoods();
        })
    },
    /* 自定义时间 */
    bindMultiPickerChange: function (e) {
        var date = e.detail.value
        var startTime = this.data.dateSelector[0][e.detail.value[0]] + '-' + this.data.dateSelector[1][e.detail.value[1]] + '-' + this.data.dateSelector[2][e.detail.value[2]]
        var endTime = this.data.dateSelector[3][e.detail.value[3]] + '-' + this.data.dateSelector[4][e.detail.value[4]] + '-' + this.data.dateSelector[5][e.detail.value[5]]
        this.setData({
            date: this.data.dateSelector[1][e.detail.value[1]] + '-' + this.data.dateSelector[2][e.detail.value[2]] + '-' + this.data.dateSelector[4][e.detail.value[4]] + '-' + this.data.dateSelector[5][e.detail.value[5]],
            multiIndex: e.detail.value,
            days: '',
            startTime: startTime,
            endTime: endTime
        })
        this.survey('')
    },
    /* 点击选择时间 */
    handleSummary(e) {
        var dateIndex = e.currentTarget.dataset['index']; //日期
        this.setData({
            days: dateIndex,
            startTime: '',
            endTime: ''
        })
        this.survey(dateIndex)
    },
    // 跳转铺货
    task: function (e) {
        wx.navigateTo({
            url: "/pages/goods/task/index?dealerId=" + JSON.stringify(e.currentTarget.dataset.dealerid) + "&goodsId=" + JSON.stringify(e.currentTarget.dataset.goodsid)
        })
    },
    // 跳转订单信息
    taskInfo: function (e) {
        wx.navigateTo({
            url: "/pages/goods/taskInfo/index?dealerId=" + JSON.stringify(e.currentTarget.dataset.dealerid) + "&goodsId=" + JSON.stringify(e.currentTarget.dataset.goodsid)
        })
    },
    // 跳转铺店概况
    store: function (e) {
        wx.navigateTo({
            url: '/pages/goods/storeSurvey/index'
        })
    },
    // 跳转铺货概况
    goods: function (e) {
        wx.navigateTo({
            url: '/pages/goods/goodSurvey/index'
        })
    },
    // 顶部tab切换
    tabSelect: function (e) {
        let index = e.currentTarget.dataset.current
        if (this.data.currTab == index) {
            return false
        } else {
            this.setData({
                currTab: index
            })
        }
        this.one_pie();
        this.two_pie();
        this.trend();
    },
    // 状态tab切换
    stateTop(e) {
        this.setData({
            staNav: e.currentTarget.dataset.item,
            ['goods.pageNum']: 1,
            awaitgoods: ''
        })
        this.awaitGoods(); //任务执行铺货
    },
    // 全部店铺显示隐藏
    btn: function () {
        var that = this;
        if (!this.data.show_centent) {
            this.setData({
                if_show: true,
                show_centent: true
            })
            that.allStore()
        } else {
            that.setData({
                show_centent: false
            })
            setTimeout(function () {
                that.setData({
                    if_show: false
                })
            }, 1000)
        }
    },
    // 显示隐藏拒绝弹框
    cancle: function () {
        this.setData({
            await: this.data.await == "none" ? "block" : 'none'
        })
    },
    //折叠面板
    isOpen: function (e) {
        var that = this;
        var idx = e.currentTarget.dataset.index;
        that.setData({
            ['awaitgoods.[' + idx + '].hidden']: that.data.awaitgoods[idx].hidden ? false : true
        })
    },
})